package com.coin.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.*;
import org.springframework.cloud.gateway.filter.*;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.*;
import org.springframework.http.server.reactive.*;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.*;

import java.util.List;

/**
 * @Auther: 李 力
 * @Date: 2025/5/23
 * @Description: com.coin.gateway.filter
 * @version: 1.0
 */
@Component
@Slf4j
public class JWTCheckFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //todo 暂且写死
    @Value("${token.whitelist:/admin/login,/user/gt/register,/user/login,/user/users/register}")
    private List<String> whitelist;

    /*
     * 过滤器的优先级
     * */
    @Override
    public int getOrder() {
        return 0;
    }

    /*
     * 过滤器拦截到用户请求的处理逻辑
     * */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.不需要检查的请求：放行
        boolean requireToken = isRequireToken(exchange);
        if (requireToken) {
            //2.取出用户token
            String token = getToken(exchange);
            if (StringUtils.isEmpty(token)) {
                return buildUNAuthorizedResult(exchange, "请携带token访问资源");
            }
            //3.判断用户token是否有效: 暂时这么写
            Boolean aBoolean = stringRedisTemplate.hasKey(token);
            if (aBoolean == null || !aBoolean) {
                return buildUNAuthorizedResult(exchange, "redis中token为空");
            }
//            //4.给token延期时间
//            stringRedisTemplate.expire(token, 180, TimeUnit.SECONDS);
            return chain.filter(exchange);
        } else {
            return chain.filter(exchange);
        }
    }


    /*
     * 判断该请求是否需要携带token
     * */
    private boolean isRequireToken(ServerWebExchange exchange) {
        String path = exchange.getRequest().getURI().getPath();
        log.info("白名单:" + whitelist.toString());
        log.info("经过网关的请求url:" + path);
        if (whitelist == null || whitelist.isEmpty()) {
            return true;
        }
        return !whitelist.contains(path);
    }

    /*
     * 获取用户token
     * */
    private String getToken(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();
        List<String> list = headers.get(HttpHeaders.AUTHORIZATION);
        if (list == null || list.isEmpty()) {
            return null;
        }
        String token = list.get(0);
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        return token.replace("Bearer ", "");
    }

    /*
     * 构建没有token或者token不合法或者token过期的响应结果
     */
    private Mono<Void> buildUNAuthorizedResult(ServerWebExchange exchange, String message) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().set("Content-Type", "application/json;charset=UTF-8");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error", "unauthorized");
        jsonObject.put("error_description", message);
        DataBuffer dataBuffer = response.bufferFactory().wrap(jsonObject.toJSONString().getBytes());
        return response.writeWith(Flux.just(dataBuffer));
    }
}
